% mtg_dist.m - compute the src-det distance for each channel
% updated 3-8-04
% creates an output file in the format n_dets x (n_configs*n_mux) (row x col)
%  it puts it in EXP\reg\ with the extension .dis

% This function expects the .mtg file in EXP\opt-crd,
% and the .elp file in EXP\reg 

function mtg_dist(file_name,log_file)
global hdr

if ~strcmp(log_file,'')
    logid = fopen(log_file,'a');
else logid = 1; end

fprintf(logid,'mtg_dist.m\n')

mtg_file=[file_name '.mtg'];
fprintf(logid,'Reading %s\n',mtg_file)
mtg_file
[src det sensors] = read_mtg(mtg_file); %!!! wavelengths !!!
% read .elp file (defines src/det locations)

elp_file=[file_name '.elp'];

if exist(elp_file,'file')==2
	[src_xyz det_xyz]=read_elp(elp_file,src,det);
	
	% Compute distances
	%		
	for i_ch=1:size(src,2)
        sx1=src_xyz(i_ch,1);
        sx2=src_xyz(i_ch,2);
        sx3=src_xyz(i_ch,3);
        dx1=det_xyz(i_ch,1);
        dx2=det_xyz(i_ch,2);
        dx3=det_xyz(i_ch,3);
        dist(i_ch)=sqrt((sx1-dx1)^2+(sx2-dx2)^2+(sx3-dx3)^2);
	end
else
    fprintf(logid,'%s does not exist\n',elp_file);
end % file exists
dist = reshape(dist,hdr.n_srcs,[])';

n_dets = size(dist,1);

out_file = [file_name '.dis'];
fprintf(logid,'Writing .dis file:  %s\n',out_file);
fid=fopen(out_file,'w');
for i_det=1:n_dets
    fprintf(fid,'%3.1f  ',dist(i_det,:));
    fprintf(fid,'\n');
end
fclose(fid);

if logid ~= 1, fclose(logid); end
